# -*- coding: utf-8 -*
# -------------------------------------------------------------------------------
# @Create Time  : 2024/04/10 11:45
# @Author       : kony.xie
# @File Name    : mail.py
# @Python Ver.  : Python 3.8.10
# @Description  : 用来发送邮件
# -------------------------------------------------------------------------------

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import os
import logging

logging.basicConfig(
    level=logging.INFO,  # 设置日志级别为INFO，这样ERROR级别及以上的日志都会被记录
    filemode='a',  # 以追加模式打开日志文件
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'  # 设置日志格式
)
logger = logging.getLogger(__name__)

class Mail():
    def __init__(self):
        # Set the mail server information
        # Email server address
        self.mail_host = 'smtp.zkteco.com'
        # Sender email
        self.mail_user = 'TestCenter@zkteco.com'
        # Sender email password
        self.mail_pass = 'Test@456'

    def send(self, content, subject, recv):
        # Setting email Information
        message = MIMEMultipart()
        message['From'] = self.mail_user
        message['Subject'] = subject
        # The recipient of the email is displayed only as the first recipient. In fact, all the recipients are sent
        message['To'] = recv
        if os.path.isfile(content):
            text = open(content, encoding='utf-8').read()
            # Set html format parameters
            part = MIMEText(text, 'html', 'utf-8')
        else:
            part = MIMEText(content, 'plain', 'utf-8')
        # Append the content to the body of the message
        message.attach(part)

        # Sign in and send
        try:
            # If you use a cloud server, generally block the outbound port 25, to use port 587
            # smtpObj = smtplib.SMTP( mail_host, 587 )
            # smtpObj.starttls()

            smtpObj = smtplib.SMTP()
            smtpObj.connect(self.mail_host, 25)
            smtpObj.login(self.mail_user, self.mail_pass)
            smtpObj.sendmail(self.mail_user, recv, message.as_string())
            logger.info('Mail sent successfully')
            smtpObj.quit()
        except smtplib.SMTPException as e:
            logger.error('error', e)
